package com.king.zk.app;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 实时获取在线的服务器列表
 */
public class Client {


    private String connectString ="hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 10000;
    private ZooKeeper  zookeeper ;
    private String serverZnode ="/servers" ;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        Client client  = new Client() ;
        //1. 初始化Zookeeper客户端连接
        client.initConnect();

        //2. 获取在线的服务器列表
        client.listAllServers();

        //3. 保持连接
        TimeUnit.MILLISECONDS.sleep(Long.MAX_VALUE);
    }

    //循环监听
    private void listAllServers() throws KeeperException, InterruptedException {
        List<String> children = zookeeper.getChildren(serverZnode, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                // 重新获取当前在线的服务器
                try {
                    listAllServers();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        System.out.println("当前在线的服务器为: " + children);
    }

    private void initConnect() throws IOException {
        zookeeper  = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }
}
